package main

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	"github.com/kataras/iris/middleware/recover"
)

const ROOT_PATH = "./src/anan.iris/"
const APP_PATH  = ROOT_PATH + "app/"
const CFG_PATH  = ROOT_PATH + "conf/"
const PUBLIC_PATH = ROOT_PATH + "public/"
const SRC_PATH  = ROOT_PATH + "src/"
const STATIC_PATH  = PUBLIC_PATH + "static/"
const VIEW_PATH = APP_PATH + "view/"
const MODULE    = "index"
// var app;
func appInit() *iris.Application{
	app := iris.New()
	app.Logger().SetLevel("debug")
	// Optionally, add two built'n handlers
	// that can recover from any http-relative panics
	// and log the requests to the terminal.
	app.Use(recover.New())
	app.Use(logger.New())
	tpl := iris.HTML(VIEW_PATH,".tpl").
		Layout("tpl/base.tpl").
		Reload(true)
	app.RegisterView(tpl)
	// app.StaticWeb("/public",PUBLIC_PATH)
	app.OnAnyErrorCode(func(ctx iris.Context) {
		ctx.ViewData("Msg",ctx.Values().GetStringDefault("msg","404 not found"))
		ctx.View("err/404.tpl")
	})
	return app
}

// to learn 控制器/路由
func main() {
	app := appInit()

	app.Any("/{c:string}/{m:string}/{p:path}", func(ctx iris.Context){
        // cm := ctx.Method()
        // cp := ctx.Path()
        // ctx.Writef("Hello from method: %s and path: %s and param : %s\n", cm, cp,pa)
        c := ctx.Params().GetStringDefault("c","error")
		m := ctx.Params().GetStringDefault("m","index")
		// p := ctx.URLParamDefault("p","") ?p=2
		ctx.Writef("Hello from c: %s and m: %s  and p: %s\n", c, m ,p)
	})

	app.Any("/{p:path}", func(ctx iris.Context) {
		// p := ctx.URLParamDefault("p","")
		ctx.WriteString("err/index\n")
	})

	// app.Handle("GET","/", func(ctx iris.Context) {
	// 	ctx.HTML("<h1> hello world! </h1>")
	// })
	// app.Get("/ping", func(ctx iris.Context) {
	// 	ctx.WriteString("pong")
	// })
	// app.Get("/hello", func(ctx iris.Context) {
	// 	ctx.ViewData("Title","测试页面")
	// 	ctx.ViewData("Content","hello tpl")
	// 	ctx.View("hello.tpl")
	// })
	// // app.Get("/donate",Handle1,Handle2)
	// app.Get("user/{uid:uint64 min(1)}", func(ctx iris.Context) {
	// 	uid := ctx.Params().GetUint64Default("uid",0)
	// 	ctx.JSON(iris.Map{"uid":uid})
	// })
	// // adminApp
	// v1 := app.Party("v1.")
	// userApi := v1.Party("/api/user")
	// userApi.Get("/{uid:int}", func(ctx iris.Context) {
	// 	uid := ctx.Params().GetIntDefault("uid",0)
	// 	ctx.JSON(iris.Map{"uid":uid})
	// })
	// other route
	// app.Get("{root:path}", rootWildcardHandler)

	// app.Run(iris.Addr(":8080"),iris.WithoutServerError(iris.ErrServerClosed))  // nginx stream1
	app.Run(iris.Addr(":8080"),iris.WithCharset("UTF-8"))  // nginx stream1
    // app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.YAML(
    // 	CFG_PATH + "local.yaml",
    // )))  // nginx stream1
	// app.Run(iris.Addr(":8081"))     // nginx stream2
	// the sample cache(redis/..) best / manual
}
